package com.example.user.myfirstapp;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;

import com.bumptech.glide.Glide;
import com.example.user.myfirstapp.activity.LoginActivity;
import com.example.user.myfirstapp.activity.UserCenterActivity;
import com.example.user.myfirstapp.common.Constant;
import com.example.user.myfirstapp.entity.UserInfo;
import com.example.user.myfirstapp.fragment.HomeFragment;
import com.example.user.myfirstapp.fragment.SearchFragment;
import com.example.user.myfirstapp.fragment.ShopcarFragment;
import com.example.user.myfirstapp.fragment.TypeFragment;
import com.example.user.myfirstapp.fragment.UserFragment;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.makeramen.roundedimageview.RoundedImageView;

public class MainActivity extends FragmentActivity implements View.OnClickListener{
    private final int openFragmentCode = 4;
    //左侧滑动菜单,public,其他fragment会调用这个变量
    public SlidingMenu slideMenu;
    private Intent intent;
    private SharedPreferences sp;
    private TextView lm_tv_home,lm_tv_showName;
    public FragmentManager fragmentManager;
    private RoundedImageView iv_userHeadImg;
    private LinearLayout ll_userBox;
    private boolean isLogin=false;
    //activity_main.xml中的FrameLayout的id
    private int containerId;
    //底部菜单LinearLayout集合
    private ArrayList<LinearLayout> LinearLayoutList;
    //Fragment
    private Fragment homeFragment;
    private Fragment typeFragment;
    private Fragment searchFragment;
    private Fragment shopcarFragment;
    private Fragment userFragment;

    //分类页面左侧一级分类选中项的position
    public int type_left_position;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fragmentManager = getSupportFragmentManager();
        //activity_main.xml中的FrameLayout的id
        containerId=R.id.fl_content;
        //初始化左侧菜单
        initSlideMenu();
        //初始化控件
        initControl();
        /**
         * 默认显示homeFragment
         * homeFragment=0,typeFragment=1,searchFragment=2,shopcarFragment=3,userFragment=4
         */
        intent =getIntent();
        int frg=intent.getIntExtra("openFragmentCode",0);
        //修改密码或修改头像后会需打开用“我的”页面
        if(frg==4){
            resetBotton();
            setClickedColor(4);
            userFragment = new UserFragment();
            addAndShowFragment(userFragment);
        }
        else {
            homeFragment = new HomeFragment();
            addAndShowFragment(homeFragment);
        }
    }

    //初始化左侧菜单
    private void initSlideMenu(){
        slideMenu=new SlidingMenu(this);
        slideMenu.setMode(SlidingMenu.LEFT);
        //设置触摸屏幕的模式
        slideMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        //设置滑动菜单视图的宽度
        slideMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
        //设置渐入渐出效果的值
        slideMenu.setFadeDegree(0.35f);
        //把滑动菜单添加进所有的Activity中，可选值SLIDING_CONTENT ， SLIDING_WINDOW
        slideMenu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
        //为侧滑菜单设置布局
        slideMenu.setMenu(R.layout.activity_main_left);
        //打开侧滑菜单监听事件
        slideMenu.setOnOpenListener(new SlidingMenu.OnOpenListener() {
            @Override
            public void onOpen() {
                onOpenLeftMenu();
            }
        });
    }

    //初始化控件
    private void initControl() {
        // 初始化底部菜单LinearLayout
        LinearLayoutList = new ArrayList<LinearLayout>();
        LinearLayoutList.add((LinearLayout) findViewById(R.id.menu_home));
        LinearLayoutList.add((LinearLayout) findViewById(R.id.menu_type));
        LinearLayoutList.add((LinearLayout) findViewById(R.id.menu_search));
        LinearLayoutList.add((LinearLayout) findViewById(R.id.menu_shopcar));
        LinearLayoutList.add((LinearLayout) findViewById(R.id.menu_users));
        //初始化底部菜单按钮事件
        for (LinearLayout linearLayout : LinearLayoutList){
            linearLayout.setOnClickListener(this);
        }

        //左侧菜单按钮
        ll_userBox=(LinearLayout)findViewById(R.id.ll_userBox);
        lm_tv_showName=(TextView)findViewById(R.id.lm_tv_showName);
        iv_userHeadImg=(RoundedImageView)findViewById(R.id.iv_userHeadImg);
        lm_tv_home=(TextView)findViewById(R.id.lm_tv_home);
        lm_tv_home.setOnClickListener(this);
        ll_userBox.setOnClickListener(this);
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.menu_home:
                resetBotton();
                setClickedColor(0);
                if(homeFragment==null){
                    homeFragment=new HomeFragment();
                    addAndShowFragment(homeFragment);
                }
                else {
                    showFragment(homeFragment);
                }
                break;
            case R.id.menu_type:
                resetBotton();
                setClickedColor(1);
                if(typeFragment==null){
                    typeFragment=new TypeFragment();
                    addAndShowFragment(typeFragment);
                }
                else {
                    showFragment(typeFragment);
                }
                break;
            case R.id.menu_search:
                resetBotton();
                setClickedColor(2);
                if(searchFragment==null){
                    searchFragment=new SearchFragment();
                    addAndShowFragment(searchFragment);
                }
                else {
                    showFragment(searchFragment);
                }
                break;
            case R.id.menu_shopcar:
                resetBotton();
                setClickedColor(3);
                if(shopcarFragment==null){
                    shopcarFragment=new ShopcarFragment();
                    addAndShowFragment(shopcarFragment);
                }
                else {
                    showFragment(shopcarFragment);
                }
                break;
            case R.id.menu_users:
                resetBotton();
                setClickedColor(4);
                if(userFragment==null){
                    userFragment=new UserFragment();
                    addAndShowFragment(userFragment);
                }
                else {
                    showFragment(userFragment);
                }
                break;
            case R.id.lm_tv_home:
                resetBotton();
                setClickedColor(0);
                //关闭左侧菜单
                if(slideMenu.isMenuShowing()) {
                    slideMenu.toggle();
                }
                if(homeFragment==null){
                    homeFragment=new HomeFragment();
                    addAndShowFragment(homeFragment);
                }
                else {
                    showFragment(homeFragment);
                }
                break;
            case R.id.ll_userBox:
                if(isLogin){
                    intent = new Intent(this, UserCenterActivity.class);
                    startActivity(intent);
                    //从右往左切换
                    overridePendingTransition(R.animator.slide_right_in,0);
                }
                else {
                    intent = new Intent(this, LoginActivity.class);
                    startActivity(intent);
                    overridePendingTransition(R.animator.slide_bottom_in,0);
                }
            default:
                break;
        }
    }

    //显示Fragment
    public void showFragment(Fragment fragment) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.show(fragment);
        transaction.commit();
    }

    //添加并显示Fragment
    public void addAndShowFragment(Fragment fragment) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.add(containerId, fragment);
        transaction.show(fragment);
        transaction.commit();
    }

    //隐藏Fragment
    public void hideFragment(Fragment fragment) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        if(fragment != null) {
            transaction.hide(fragment);
        }
        transaction.commit();
    }

    //点击底部菜单前的设置
    public void resetBotton(){
        // 在每次点击后将所有的底部按钮颜色改为灰色，然后根据点击着色
        for (LinearLayout linearLayout : LinearLayoutList){
            linearLayout.setBackgroundColor(getResources().getColor(R.color.colorMainBottom));
            //或者ll_home.setBackgroundColor(0xff000000)
        }
        //隐藏所有Fragment
        hideFragment(homeFragment);
        hideFragment(typeFragment);
        hideFragment(searchFragment);
        hideFragment(shopcarFragment);
        hideFragment(userFragment);
    }

    //设置底部菜单LinearLayout点击后的颜色
    public void setClickedColor(int position) {
        LinearLayout linearLayout = LinearLayoutList.get(position);
        linearLayout.setBackgroundColor(getResources().getColor(R.color.colorMainBottomClicked));
    }

    //打开侧滑菜单监听事件
    private void onOpenLeftMenu() {
        //从SharedPreferences读取用户信息
        sp = getSharedPreferences(Constant.sharedPreferences_user_key, Context.MODE_PRIVATE);
        String userJson = sp.getString("userJson", "");
        if (!TextUtils.isEmpty(userJson)) {
            Gson gson = new Gson();
            UserInfo user = gson.fromJson(userJson, new TypeToken<UserInfo>() {}.getType());
            String name = user.getUserName();
            String imgUrl=user.getUserImg();
            isLogin=true;
            lm_tv_showName.setText(name);
            if(!TextUtils.isEmpty(imgUrl)){
                String url="http://"+ Constant.host+":"+Constant.port+"/"+imgUrl;
                Glide.with(this).load(url).into(iv_userHeadImg);
            }
        }
        else {
            isLogin=false;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //mianActivity重新显示时，如果左侧菜单栏是打开的，需要判断是否登陆（显示用户头像、姓名等）
        if(slideMenu.isMenuShowing()) {
            onOpenLeftMenu();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        //这里可以销毁需要登录的fragment
    }
}
